<template>
  <div class="main">
    <div class="school-wrapper">
      <headerBack></headerBack>
      <div class="serach-box flex-h" @click="commonJs.gopush('searchSchool')">
        <span></span>
        <b class="flex1">请输入意向学校</b>
      </div>
      <article class="country" v-show="countryList.length > 0" v-cloak>
        <scrollerEdit lock-x @on-scroll="onScroll" ref="listview">
          <div>
            <div style="height:1.6rem"></div>
            <ul class="country-list">
              <li v-for="(group, indexs) in countryList" :key="indexs + 100" ref="listGroup">
                <h2 class="list-group-title">{{ group.title }}</h2>
                <ul>
                  <li v-for="(item, $indexs) in group.items" :key="$indexs + 1000" :class="[{ active: phoneCode == item.nationalCode }, 'list-group-item']" @click="goDetal(item.nationalCode, item.academyName)">
                    <span class="name">{{ item.academyName }}</span>
                    <!-- <span>(+{{item.nationalCode}})</span> -->
                  </li>
                </ul>
              </li>
            </ul>
          </div>
        </scrollerEdit>
        <ul class="list-shortcut" @click.stop.prevent="onShortcutTouchStart" @touchstart="onShortcutTouchStart" @touchmove.stop.prevent="onShortcutTouchMove" @touchend.stop.prevent="onShortcutTouchEnd">
          <li @mouseout.stop.prevent="onShortcutTouchEnd" :class="[{ selected: fixedTitle == item }, 'item']" v-for="(item, index) in shortcut" :key="index + 2000">{{ item }}</li>
        </ul>
        <div class="selected-shortcut" v-show="isTouch">{{ showWord }}</div>
        <div class="list-fixed" v-show="fixedTitle" ref="fixed">{{ fixedTitle }}</div>
      </article>
      <!-- </scroller> -->
    </div>
  </div>
</template>

<script>
import ls from 'store2'
import headerBack from '~/components/headerBack'
// import countryData from "~/static/json/country.json";
import scrollerEdit from '~/components/scrollerEdit'
import { getAcademys } from '~/api/selectCourse'
export default {
  data() {
    return {
      showWord: '',
      tabIndex: 0,
      // countryData: countryData,
      isTouch: false,
      countryList: [],
      shortcut: [],
      phoneCode: '93',
      touch: {},
      listHeight: [],
      scrollY: -1,
      currentIndex: 0,
      diff: -1,
      fixedTop: -1,
    }
  },
  components: {
    scrollerEdit,
    headerBack,
  },
  created() {},
  computed: {
    fixedTitle() {
      return this.shortcut[this.currentIndex] ? this.shortcut[this.currentIndex] : 'A'
    },
  },
  mounted() {
    this.$visit(this.$route.path)
    if (sessionStorage.getItem('countryList')) {
      this.countryList = JSON.parse(sessionStorage.getItem('countryList'))
      this.shortcut = JSON.parse(sessionStorage.getItem('shortcut'))
      this.$nextTick(() => {
        this.calculateTotalHeight()
      })
    } else {
      this.getAcademys()
    }
  },
  methods: {
    goDetal(code, schoolName) {
      this.phoneCode = code
      this.$router.push({
        path: 'schoolDetail?schoolCode=' + code + '&schoolName=' + schoolName,
      })
    },
    getAcademys() {
      let obj = {
        name: '',
      }
      getAcademys(obj)
        .then((res) => {
          if (res.code == '0') {
            let counData = res.data
            var _this = this
            var map = {}
            counData.forEach(function(item, index) {
              var key = item.dictionaries
              if (!map[key]) {
                _this.shortcut.push(key)
                map[key] = {
                  title: key,
                  items: [],
                }
              }
              map[key].items.push(item)
            })
            // 转为数组
            var ret = []
            for (var k in map) {
              var val = map[k]
              ret.push(val)
            }
            // 排序
            ret.sort(function(a, b) {
              return a.title.charCodeAt(0) - b.title.charCodeAt(0)
            })
            _this.shortcut.sort(function(a, b) {
              return a.charCodeAt(0) - b.charCodeAt(0)
            })

            _this.countryList = ret
            sessionStorage.setItem('countryList', JSON.stringify(_this.countryList))
            sessionStorage.setItem('shortcut', JSON.stringify(_this.shortcut))

            this.$nextTick(() => {
              _this.calculateTotalHeight()
            })
          }
        })
        .catch((err) => {})
    },
    onScroll(pos) {
      this.scrollY = pos.top
    },

    onShortcutTouchStart(e) {
      let anchorIndex = this.shortcut.indexOf(e.target.innerText)
      this.showWord = e.target.innerText
      this.tabIndex = anchorIndex
      this.currentIndex = anchorIndex
      this.touch.y1 = e.pageY ? e.pageY : e.touches[0].pageY
      this.touch.anchorIndex = anchorIndex
      this.scrollY = this.listHeight[this.currentIndex]

      // this.currentIndex = anchorIndex
      this.scrollToIndex(anchorIndex)
      this.isTouch = true
    },
    onShortcutTouchMove(e) {
      this.touch.y2 = e.touches[0].pageY
      var delta = ((this.touch.y2 - this.touch.y1) / 16) | 0
      var anchorIndex = parseInt(this.touch.anchorIndex) + parseInt(delta)
      this.scrollToIndex(anchorIndex)
      this.isTouch = true
    },
    onShortcutTouchEnd() {
      this.isTouch = false
    },
    onMouseover(index) {
      // this.tabIndex=index
      this.touch.anchorIndex = index
      this.scrollToIndex(index)
      this.isTouch = true
    },
    scrollToIndex(index) {
      this.$nextTick(() => {
        this.$refs.listview.reset({ top: this.listHeight[index] })
      })
    },
    calculateTotalHeight() {
      var list = this.$refs.listGroup
      var height = 0
      this.listHeight.push(height)
      for (var i = 0; i < list.length; i++) {
        var item = list[i]
        height += item.clientHeight
        this.listHeight.push(height)
      }
    },
  },
  watch: {
    scrollY(newY) {
      newY = newY || this.listHeight[this.currentIndex]
      var listHeight = this.listHeight
      // 当滚动到顶部时， newY<=0
      if (newY <= 0) {
        this.currentIndex = 0
        return
      }
      // 中间部分滚动
      for (var i = 0; i < listHeight.length - 1; i++) {
        var height1 = listHeight[i]
        var height2 = listHeight[i + 1]
        if (!height2 || (newY >= height1 && newY < height2)) {
          this.currentIndex = i
          this.diff = height2 - newY
          return
        }
      }
      // 滚动到底部且newY大于最后一个元素的上限
      this.currentIndex = listHeight.length - 1
    },
    diff(newVal) {
      var fixedTop = newVal - 24 < 0 ? newVal - 24 : 0
      if (this.fixedTop === fixedTop) {
        return false
      }
      this.fixedTop = fixedTop
      this.$refs.fixed.style.transform = `translate3d(-50%,${fixedTop}px,0)`
    },
  },
}
</script>

<style lang="less" scoped>
.school-wrapper {
  width: 100%;
  height: 100vh;
  background: #fff;
}
.serach-box {
  height: 0.8rem;
  padding: 0 0.3rem;
  box-sizing: border-box;
  position: relative;
  z-index: 100;
  background: #fff;
  span {
    display: inline-block;
    width: 0.4rem;
    height: 0.4rem;
    background: url('~/static/sprite/other_sprites.png') 0.42rem -0.55rem;
    background-size: 4.68rem 4.08rem;
  }
  b {
    font-size: 0.3rem;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(199, 199, 199, 1);
    // line-height:30px;
    padding-left: 0.3rem;
    box-sizing: border-box;
  }
}
[v-cloak] {
  display: none;
}

* {
  margin: 0;
  padding: 0;
  list-style: none;
  box-sizing: border-box;
}
::-webkit-scrollbar {
  display: none;
}
body {
  /*火狐下隐藏滚动条*/
  overflow: -moz-scrollbars-none;
}
.country {
  position: fixed;
  left: 0;
  right: 0;
  top: 0rem;
  bottom: 0;
  overflow-y: scroll;
  overflow-x: hidden;
  background: #f7f7fa;
  z-index: 20;
  max-width: 640px;
  margin: 0 auto;
  -webkit-tap-highlight-color: transparent;
  -webkit-overflow-scrolling: touch;
}

.country-list h2 {
  padding: 4px 16px;
  color: #8a8a8f;
  line-height: 16px;
  font: 400 14px/16px SFProText-Regular;
}

.country-list ul {
  background: #fff;
  padding: 0 16px;
}

.list-group-item {
  padding: 12px 0 12px 0;
  border-bottom: 0.01rem solid rgba(238, 238, 238, 1);
  font: 16px/20px SFProText-Regular;
  user-select: none;
  cursor: pointer;
}

.list-group-item.active {
  // background: url(./checked.png)no-repeat 4px center/18px;
  // background:yellow;
}

.country-list ul li:last-child {
  border: none;
}

.list-shortcut {
  position: fixed;
  z-index: 30;
  right: 0;
  padding-right: 8px;
  top: 50%;
  transform: translateY(-50%);
  text-align: center;
  background: #fff;
  user-select: none;
  cursor: pointer;
  width: 50px;
}
.selected-shortcut {
  position: fixed;
  top: 50%;
  left: 70%;
  width: 40px;
  height: 40px;
  margin-top: -20px;
  border-radius: 50%;
  color: #fff;
  background: #dddce0;
  text-align: center;
  font: 500 20px/40px SFProText-Regular;
}
.list-shortcut .item {
  line-height: 16px;
  color: @mainColor;
  font-size: 12px;
  font-weight: 600;
}
.list-shortcut .selected {
  color: @mainColor;
  font-weight: 600;
}
.list-fixed {
  position: fixed;
  width: 100%;
  top: 0;
  left: 50%;
  background: #f7f7fa;
  padding: 4px 16px;
  color: #8a8a8f;
  line-height: 16px;
  font: 400 14px/16px SFProText-Regular;
  max-width: 640px;
  margin: 0 auto;
  transform: translateX(-50%);
}

@media (min-width: 640px) {
  .list-shortcut {
    right: 50%;
    margin-right: -320px;
  }

  .list-shortcut .item {
    padding: 0 10px;
  }
}
</style>
